<?php

require_once("DBConfig.php");

class Database
{
	private $mysqli = NULL;
	
	public function Connect(DBConfig $config)
	{
		$this->mysqli = new mysqli($config->host,
							$config->user,
							$config->password,
							$config->db);
		
		if($this->mysqli->connect_error)
		{
			throw new Exception($this->mysqli->connect_error);
		}	
		
		$this->mysqli->set_charset("utf-8");
		
		return TRUE;
	}
	
	public function Select($sqlQuery) 
	{			
		//Ansluter till Databasen	
		$config = new DBConfig();	
		$this->Connect($config);	
		
		//Förbereder en SQL sats
		$stmt = $this->mysqli->prepare($sqlQuery);
		 
		//Kollar så att förberedelsen godkänns. 
		if($stmt == FALSE)
		{
			throw new Exception($this->mysqli->error);
        }
		 
		//Testar att exekvera SQL satsen		 
		if($stmt->execute() == FALSE)
		{
			throw new Exception($this->mysqli->error);
		}
		 
		$ret = 0;
		 
		//Testar att binda resultatet till $ret 
		if($stmt->bind_result($ret) == FALSE)
		{
			throw new Exception($this->mysqli->error);
		}
		  
		//Sätter resultatet till variabeln  		  
		$stmt->fetch();
		
		$stmt->close();		 
		
		return $ret;	 
	}
	
	public function Close()
	{
		return $this->mysqli->close();
	}	
			
	public static function Test(DBConfig $dbConfig)
	{
		$db = new Database();
		
		if($db->Connect($dbConfig) == FALSE)
		{
			echo "Databasanslutning misslyckades";
			return FALSE;
		}
		
		if($db->Close() == FALSE)
		{
			echo "Stängning av databasanslutning misslyckades";
			return FALSE;			
		}
		
		return TRUE;
	}
	
}

?>
